const Base = require('./base.js');

module.exports = class extends Base {
  _isCheckLogin() {
    return true; // 确保用户登录后才能操作购物车
  }

  async getAddressAction() {
    try {
      const user = await this.ctx.session('login');
      if (!user || !user.id) {
        return this.fail('用户未登录，请先登录');
      }
      // 查询当前用户的收货地址
      const addressModel = think.model('address');
      const data = await addressModel.where({ user_id: user.id }).select();

      // 判断地址是否为空
      if (think.isEmpty(data)) {
        return this.success([], '地址为空');
      }

      return this.success(data, '获取地址成功');
    } catch (error) {
      console.error('获取地址时发生错误:', error);
      return this.fail('获取地址失败，请稍后再试');
    }
  }

  // 添加地址信息
  async addAddressAction() {
    try {
      const user = await this.ctx.session('login');
      if (!user || !user.id) {
        return this.fail('用户未登录，请先登录！');
      }

      // 获取前端传递的参数
      const { province, city, detail, phone } = this.post();

      if (!province || !city || !detail || !/^\d{11}$/.test(phone)) {
        return this.fail('你填写的信息有误，请重新填写');
      }

      // 初始化地址模型
      const addressModel = think.model('address');

      // eslint-disable-next-line no-console
      console.log(addressModel);

      //
      await addressModel.add({
        province,
        city,
        detail,
        phone,
        user_id: user.id
      });
      return this.success({}, '添加地址成功，如果没有更新，请刷新网页');
    } catch (error) {
      console.error('添加地址时发生错误', error);
      return this.fail('添加商品到购物车失败,请稍后再试');
    }
  }
};
